package com.ytxg.home.service.impl;


import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ytxg.api.feign.BookInfoClient;
import com.ytxg.api.po.book.BookInfo;
import com.ytxg.api.po.home.HomeBook;
import com.ytxg.core.consts.DatabaseConsts;
import com.ytxg.core.dto.RestResp;
import com.ytxg.home.dto.HomeBookRespDto;
import com.ytxg.home.mapper.HomeBookMapper;
import com.ytxg.home.service.IHomeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class HomeServiceImpl implements IHomeService {


    private final HomeBookMapper homeBookMapper;


    private final BookInfoClient bookInfoClient;



    @Override
    public RestResp<List<HomeBookRespDto>> listHomeBooks() {
        // 从首页小说推荐表中查询出需要推荐的小说
        QueryWrapper<HomeBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc(DatabaseConsts.CommonColumnEnum.SORT.getName());
        List<HomeBook> homeBooks = homeBookMapper.selectList(queryWrapper);//获取到所有homeBook

        //id和type绑定
        Map<Long,Byte> map = new HashMap<>();
        for (HomeBook homeBook : homeBooks) {
            map.put(homeBook.getBookId(),homeBook.getType());
        }
        //id列表
        List<Long> ids = new ArrayList<>();
        for (HomeBook homeBook : homeBooks) {
            Long bookId = homeBook.getBookId();
            ids.add(bookId);
        }

        List<BookInfo> bookInfoList = bookInfoClient.getBookInfoList(ids);

        List<HomeBookRespDto> ret = new ArrayList<>();//返回
        // 组装 HomeBookRespDto 列表数据并返回
        if (!CollectionUtils.isEmpty(bookInfoList)) {
            for (BookInfo bookInfo : bookInfoList) {
                HomeBookRespDto homeBookRespDto = new HomeBookRespDto();
                homeBookRespDto.setType(map.get(bookInfo.getId()));
                homeBookRespDto.setBookId(bookInfo.getId());
                homeBookRespDto.setBookName(bookInfo.getBookName());
                homeBookRespDto.setPicUrl(bookInfo.getPicUrl());
                homeBookRespDto.setAuthorName(bookInfo.getAuthorName());
                homeBookRespDto.setBookDesc(bookInfo.getBookDesc());
                ret.add(homeBookRespDto);
            }
        }

        return RestResp.ok(ret);

    }
}